//
//  InfiniteSelectViewController.m
//  Uhomebk
//
//  Created by Chiang on 16/11/8.
//  Copyright © 2016年 com.segi. All rights reserved.
//

#import "InfiniteSelectViewController.h"
static NSString * childkey = @"child";
@implementation InfiniteSelectViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self showCustomNavigationRightButtonWithTitle:@"保存" image:nil hightlightImage:nil color:kColor_T];
    
    [self setupUI];
    
    _lastDataArr = [NSMutableArray array];
    
    num = 0;
    
    _dataArray = _value;
    [self setHasChildValue:_dataArray];
    if (_childId) {
        _dataArr = [self getChildArrayWithId:_childId dataArray:_dataArray];
    } else {
        _dataArr=[self getRootArray:_dataArray];
    }
    
    if (_dataArr) {
        [_lastDataArr addObject:_dataArr];
    }
    
    [self seg_SetDefaultValue];
    
}

- (void)setupUI {
    self.view.backgroundColor = kColor_bg;
    
    self.typeTableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    self.typeTableView.dataSource = self;
    self.typeTableView.delegate = self;
    self.typeTableView.backgroundColor = kColor_bg;
    self.typeTableView.separatorColor = kColor_L2;
    self.typeTableView.tableFooterView = [[UIView alloc] init];
    [self.view addSubview:self.typeTableView];
    
    headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, LYScreenWidth(), 44)];
    headerView.backgroundColor = kColor_W;
    UILabel* backLabel = [[UILabel alloc] initWithFrame:CGRectMake(20, 0, 80, 44)];
    backLabel.textColor = kColor_1;
    backLabel.font = kFont_15;
    backLabel.backgroundColor = kColor_W;
    backLabel.text = @"返回上一层";
    [headerView addSubview:backLabel];
    
    UITapGestureRecognizer* tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction:)];
    [headerView addGestureRecognizer:tap];
    
    [self.typeTableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.mas_equalTo(0);
        make.top.mas_equalTo(0);
    }];
}

-(void)seg_SetDefaultValue {
    if (_defaultValue) {
        NSDictionary *dic = [SEGUtils dictionaryWithJsonString:_defaultValue];
        for (NSDictionary *dict in _dataArray) {
            if ([[SEGUtils ValueToString:dic[@"id"]] isEqualToString:[SEGUtils ValueToString:dict[@"positionId"]]]) {
                [dict setValue:@"1" forKey:@"sel"];
            }
        }
    }
}

#pragma mark - 编辑保存
- (void)onNavigationRightButtonClicked:(UIButton*)sender
{
    if (self.fundelegate) {
        [self.fundelegate returnSelectedData:[self getSelectedData]];
    }
    [self.navigationController popViewControllerAnimated:YES];
}

- (NSString*)dictionaryToJson:(NSDictionary*)dic
{
    NSError* parseError = nil;
    
    NSData* jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&parseError];
    
    return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}

#pragma mark - TableViewDelegate
- (NSInteger)tableView:(UITableView*)tableView numberOfRowsInSection:(NSInteger)section
{
    return _dataArr.count;
}

- (CGFloat)tableView:(UITableView*)tableView heightForRowAtIndexPath:(NSIndexPath*)indexPath
{
    return 44;
}
- (CGFloat)tableView:(UITableView*)tableView heightForHeaderInSection:(NSInteger)section
{
    if (num > 0) {
        return 44;
    }
    else {
        return 0.1;
    }
}
- (UIView*)tableView:(UITableView*)tableView viewForHeaderInSection:(NSInteger)section
{
    if (num > 0) {
        return headerView;
    }
    else {
        return nil;
    }
}
- (UITableViewCell*)tableView:(UITableView*)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath
{
    NSString* cellStr = [NSString stringWithFormat:@"%ld", (long)indexPath.row];
    UITableViewCell* cell = [tableView cellForRowAtIndexPath:indexPath];
    UIImage* image = [UIImage imageWithContentsOfFile:SEGPicName(@"btn_list_select_nor")];
    
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellStr];
        
        UIImageView* selectView = [[UIImageView alloc] initWithFrame:CGRectMake(20, (44 - image.size.height) / 2, image.size.width, image.size.height)];
        selectView.image = image;
        selectView.tag = 1000 + indexPath.row;
        [cell.contentView addSubview:selectView];
        
        UILabel* title = [[UILabel alloc] initWithFrame:CGRectMake(30 + image.size.width, 0, 200, 44)];
        title.textColor = kColor_1;
        title.font = kFont_15;
        title.tag = 2000;
        [cell.contentView addSubview:title];
    }
    UIImageView* selectView = (UIImageView*)[cell viewWithTag:1000 + indexPath.row];
    UILabel* title = (UILabel*)[cell viewWithTag:2000];
    

    if ([_type isEqualToString:@"2"]) {
        title.text = [_dataArr[indexPath.row] objectForKey:@"positionName"];
        
        if ([[_dataArr[indexPath.row] objectForKey:@"hasChild"] isEqualToString:@"1"]) {
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
            selectView.hidden = YES;
            title.frame = CGRectMake(20, 0, 200, 44);
        }
        else {
            cell.accessoryType = UITableViewCellAccessoryNone;
            selectView.hidden = NO;
            title.frame = CGRectMake(30 + image.size.width, 0, 200, 44);
            selectView.frame = CGRectMake(20, (44 - image.size.height) / 2, image.size.width, image.size.height);
        }
        if ([[_dataArr[indexPath.row] objectForKey:@"sel"] isEqualToString:@"1"]) {
            selectView.image = [UIImage imageWithContentsOfFile:SEGPicName(@"btn_list_select")];
        }
        else {
            selectView.image = [UIImage imageWithContentsOfFile:SEGPicName(@"btn_list_select_nor")];
        }
    }
    
    return cell;
}

- (void)tableView:(UITableView*)tableView didSelectRowAtIndexPath:(NSIndexPath*)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    NSDictionary *selectDic = _dataArr[indexPath.row];
    if ([selectDic[@"hasChild"] isEqualToString:@"1"]) {

        num++;
        _childId = [SEGUtils ValueToString:selectDic[@"positionId"]];
        _dataArr = [self getChildArrayWithId:_childId dataArray:_dataArray];
        if (_dataArr) {
            [_lastDataArr addObject:_dataArr];
        }

    } else {

        if ([selectDic[@"sel"] isEqualToString:@"1"]) {
            [self setUnSelectedStatus:selectDic];
        } else {
            [self clearAllStatus:_dataArray];
            [self setSelectedStatus:selectDic];
        }
    }

    [tableView reloadData];

}
- (void)tapAction:(UITapGestureRecognizer*)tap
{
    num--;
    if(num<0)return;
    _dataArr = _lastDataArr[num];
    [_lastDataArr removeLastObject];
    [self.typeTableView reloadData];
}

#pragma mark - Methods
/**
 设置为选中状态，选择的数据
 */
- (void)setSelectedStatus:(NSDictionary *)dic {
    [dic setValue:@"1" forKey:@"sel"];
    
}

/**
 设置为未选中状态，选择的数据
 */
- (void)setUnSelectedStatus:(NSDictionary *)dic {
    [dic setValue:@"0" forKey:@"sel"];
}

/**
 清除所有状态
 */
- (void)clearAllStatus:(NSArray *)arr {
    for (NSDictionary *dic in arr) {
        [dic setValue:@"0" forKey:@"sel"];
    }
}
/**
 获取根节点
 @param dataArray 数据源数组
 */
- (NSArray *)getRootArray:(NSArray *)dataArray {
    NSMutableArray *rootArray = [NSMutableArray array];
    for (NSDictionary *dic in dataArray) {
        if ([[SEGUtils ValueToString:dic[@"upPositionId"]] isEqualToString:@"-1"]) {
            [rootArray addObject:dic];
        }
    }
    return rootArray;
}

/**
 获取子节点数组
 @param categoryId 父节点ID
 @param dataArray 数据源数组
 */
- (NSArray *)getChildArrayWithId:(NSString *)categoryId dataArray:(NSArray *)dataArray {
    NSMutableArray *childArray = [NSMutableArray array];
    for (NSDictionary *dic in dataArray) {
        if ([[SEGUtils ValueToString:dic[@"upPositionId"]] isEqualToString:[SEGUtils ValueToString:categoryId]]) {
            [childArray addObject:dic];
        }
    }
    return childArray;
}

-(void)setHasChildValue:(NSArray *)dataArray {
    for (NSDictionary *dict in dataArray) {
        for (NSDictionary *dic in dataArray) {
            if ([[SEGUtils ValueToString:dic[@"upPositionId"]] isEqualToString:[SEGUtils ValueToString:dict[@"positionId"]]]) {
                [dict setValue:@"1" forKey:@"hasChild"];
                break;
            }
        }
    }
}

/**
 查找根节点
 */
-(NSDictionary *)getRootSelectDic:(NSString *)upPositionId {
    NSDictionary *dict = nil;
    for (NSDictionary *dic in _dataArray) {
        if ([[SEGUtils ValueToString:upPositionId] isEqualToString:[SEGUtils ValueToString:dic[@"positionId"]]]) {
            if ([[SEGUtils ValueToString:dic[@"upPositionId"]] isEqualToString:@"-1"]) {
                return dic;
            } else {
                return  [self getRootSelectDic:[SEGUtils ValueToString:dic[@"upPositionId"]]];
            }
        }
    }
    return dict;
}


/**
 查找父节点
 */
-(NSDictionary *)getFatherSelectDic:(NSString *)upPositionId {
    NSDictionary *dict = nil;
    for (NSDictionary *dic in _dataArray) {
        if ([[SEGUtils ValueToString:upPositionId] isEqualToString:[SEGUtils ValueToString:dic[@"positionId"]]]) {
            dict = dic;
            break;
        }
    }
    return dict;
}

/**
 获取选中的值
 */
- (NSDictionary *)getSelectedData {
    NSDictionary *selectedDic;
    for (NSDictionary *dic in _dataArray) {
        if ([dic[@"sel"] isEqualToString:@"1"]) {
            selectedDic = dic;
            break;
        }
    }
    return selectedDic;
}



@end
